import { request } from '../../request/index'
//使用async await需要引入，只引入就行
import regeneratorRuntime from '../../lib/runtime/runtime'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    tabs: [
      { id: 0, value: "综合", isActive: true },
      { id: 1, value: "销量", isActive: false },
      { id: 2, value: "价格", isActive: false }
    ],
    goodsList:[],
    pages:0,
    triggered:false
  },
  

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    this.params.cid = options.cid || ''
    this.params.query = options.query || ''
    this.getGoodsList()

  },

  //初始化请求参数
  params:{
    query:'',
    cid:'',
    pagenum:1,
    pagesize:10
  },

  //处理点击tabcontral事件
  handleTabItemChange(event) {
    // console.log(event)
    const { index } = event.detail
    let tabs = this.data.tabs
    tabs.map(item => item.id === index ? item.isActive = true : item.isActive = false)
    this.setData({tabs})
  },
  //获取列表数据
  async getGoodsList(){
    const result = await request({url:'/goods/search',data:this.params})
    console.log(result)
    const {goods, total} = result.data.message
    this.setData({
      goodsList:[...this.data.goodsList,...goods],
      pages:Math.ceil(total/this.params.pagesize)
    })
  },

  //srocll-view下拉事件触发
  async onRefresh() {
    this.params.pagenum = 1
    const result = await request({url:'/goods/search',data:this.params})
    const {goods, total} = result.data.message
    this.setData({
      goodsList:goods,
      pages:Math.ceil(total/this.params.pagesize),
      triggered:false
    })
  },
  //srocll-view下拉复位
  onRestore() {
    // console.log('复位')
    // this.setData({triggered:false})
  },

  //scroll-view滚动到底部事件
  scrollBottom(event) {
    console.log( event)
    this.params.pagenum++
    const { pagenum } = this.params
    const { pages } = this.data
    if(pagenum > pages){
      wx.showToast({
        title: '已经到底啦~',
        icon: 'none',
        duration: 1500,
        mask: true
      })
    }else{
      this.getGoodsList()
    }

  },

  //跳转到详情页面
  jumpDetail(event) {
    console.log('跳转',event)
    const { id } = event.currentTarget.dataset
    wx.navigateTo({
      url: '/pages/goods_detail/goods_detail?id=' + id,
      event:{
        id
      }
    });
  },

})